<template>
  <div class="report-manager">
    <el-dialog 
      v-model="visible" 
      title="报表管理" 
      width="800px"
      @close="handleClose">
      
      <div class="manager-header">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索报表..."
          clearable
          style="width: 300px;">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <div class="header-actions">
          <el-button @click="refreshReports">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-upload
            :auto-upload="false"
            :show-file-list="false"
            accept=".json"
            @change="handleImportFile">
            <el-button>
              <el-icon><Upload /></el-icon>
              导入报表
            </el-button>
          </el-upload>
        </div>
      </div>
      
      <div class="reports-list">
        <el-table 
          :data="filteredReports" 
          stripe 
          @row-click="handleRowClick">
          <el-table-column prop="name" label="报表名称" min-width="200">
            <template #default="{ row }">
              <div class="report-name">
                <el-icon><Document /></el-icon>
                <span>{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="visualizations" label="组件数量" width="100">
            <template #default="{ row }">
              {{ row.config.visualizations?.length || 0 }}
            </template>
          </el-table-column>
          
          <el-table-column prop="createdAt" label="创建时间" width="150">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="updatedAt" label="修改时间" width="150">
            <template #default="{ row }">
              {{ formatDate(row.updatedAt) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button 
                size="small" 
                type="primary" 
                @click.stop="loadReport(row.id)">
                打开
              </el-button>
              <el-button 
                size="small" 
                @click.stop="duplicateReport(row.id)">
                复制
              </el-button>
              <el-dropdown @command="handleCommand($event, row)">
                <el-button size="small">
                  更多<el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="rename">重命名</el-dropdown-item>
                    <el-dropdown-item command="export">导出</el-dropdown-item>
                    <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        
        <div v-if="!filteredReports.length" class="empty-state">
          <el-icon size="48" color="#c0c4cc"><Document /></el-icon>
          <p>{{ searchKeyword ? '没有找到匹配的报表' : '暂无保存的报表' }}</p>
        </div>
      </div>
      
      <div class="manager-footer">
        <div class="stats">
          <span>共 {{ reports.length }} 个报表</span>
          <span>存储大小: {{ formatSize(stats.storageSize) }}</span>
        </div>
        
        <div class="footer-actions">
          <el-button @click="cleanupReports">清理过期报表</el-button>
          <el-button type="danger" @click="clearAllReports">清空所有</el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 重命名对话框 -->
    <el-dialog 
      v-model="showRenameDialog" 
      title="重命名报表" 
      width="400px">
      <el-input 
        v-model="newReportName" 
        placeholder="请输入新的报表名称"
        @keyup.enter="confirmRename" />
      
      <template #footer>
        <el-button @click="showRenameDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmRename">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useTableStore } from '../stores/tableStore'
import { 
  getSavedReports, 
  loadReport as loadReportUtil,
  deleteReport,
  duplicateReport as duplicateReportUtil,
  updateReport,
  exportReportAsJSON,
  importReportFromJSON,
  getReportStats,
  cleanupOldReports,
  searchReports
} from '../utils/reportUtils'
import { 
  Search, 
  Refresh, 
  Upload, 
  Document, 
  ArrowDown 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'report-loaded'])

const tableStore = useTableStore()

// 响应式数据
const visible = ref(props.modelValue)
const reports = ref([])
const searchKeyword = ref('')
const showRenameDialog = ref(false)
const newReportName = ref('')
const currentReportId = ref('')
const stats = ref({})

// 计算属性
const filteredReports = computed(() => {
  if (!searchKeyword.value) return reports.value
  return searchReports(searchKeyword.value)
})

// 监听器
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    refreshReports()
  }
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 方法
const refreshReports = () => {
  reports.value = getSavedReports()
  stats.value = getReportStats()
}

const handleRowClick = (row) => {
  // 双击打开报表
  loadReport(row.id)
}

const loadReport = (reportId) => {
  const report = loadReportUtil(reportId)
  if (report) {
    // 加载报表配置到store
    tableStore.reportConfig = { ...report.config }
    
    // 如果报表有数据源配置，也要加载
    if (report.config.dataSource) {
      // 这里可以加载特定的数据源
    }
    
    ElMessage.success(`已加载报表: ${report.name}`)
    emit('report-loaded', report)
    handleClose()
  } else {
    ElMessage.error('报表加载失败')
  }
}

const duplicateReport = (reportId) => {
  const newReportId = duplicateReportUtil(reportId)
  if (newReportId) {
    refreshReports()
    ElMessage.success('报表复制成功')
  } else {
    ElMessage.error('报表复制失败')
  }
}

const handleCommand = (command, row) => {
  switch (command) {
    case 'rename':
      currentReportId.value = row.id
      newReportName.value = row.name
      showRenameDialog.value = true
      break
    case 'export':
      exportReportAsJSON(row.id)
      ElMessage.success('报表导出成功')
      break
    case 'delete':
      confirmDelete(row)
      break
  }
}

const confirmRename = () => {
  if (!newReportName.value.trim()) {
    ElMessage.warning('请输入报表名称')
    return
  }
  
  const report = reports.value.find(r => r.id === currentReportId.value)
  if (report) {
    updateReport(currentReportId.value, report.config, newReportName.value)
    refreshReports()
    ElMessage.success('重命名成功')
  }
  
  showRenameDialog.value = false
}

const confirmDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除报表 "${row.name}" 吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger'
    }
  ).then(() => {
    deleteReport(row.id)
    refreshReports()
    ElMessage.success('报表删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

const handleImportFile = async (file) => {
  try {
    const reportId = await importReportFromJSON(file.raw)
    refreshReports()
    ElMessage.success('报表导入成功')
  } catch (error) {
    ElMessage.error(`导入失败: ${error.message}`)
  }
}

const cleanupReports = () => {
  ElMessageBox.confirm(
    '确定要清理30天前的报表吗？',
    '清理过期报表',
    {
      confirmButtonText: '清理',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const cleanedCount = cleanupOldReports(30)
    refreshReports()
    ElMessage.success(`已清理 ${cleanedCount} 个过期报表`)
  }).catch(() => {
    // 用户取消
  })
}

const clearAllReports = () => {
  ElMessageBox.confirm(
    '确定要清空所有报表吗？此操作不可恢复！',
    '清空所有报表',
    {
      confirmButtonText: '清空',
      cancelButtonText: '取消',
      type: 'error',
      confirmButtonClass: 'el-button--danger'
    }
  ).then(() => {
    localStorage.removeItem('powerbi_reports')
    refreshReports()
    ElMessage.success('所有报表已清空')
  }).catch(() => {
    // 用户取消
  })
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const formatSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const handleClose = () => {
  visible.value = false
}

// 初始化
refreshReports()
</script>

<style scoped>
.manager-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.reports-list {
  min-height: 400px;
}

.report-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-state p {
  margin-top: 16px;
  font-size: 14px;
}

.manager-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.stats {
  display: flex;
  gap: 20px;
  font-size: 13px;
  color: #606266;
}

.footer-actions {
  display: flex;
  gap: 8px;
}
</style>

